package com.nowcoder.community.controller;

import com.google.code.kaptcha.Producer;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.utils.CommunityConstant;
import com.nowcoder.community.utils.CommunityUtil;
import com.nowcoder.community.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController implements CommunityConstant {


    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private Producer kaptchaProducer;

    @Value("server.servlet.context-path")
    private String contextPath;
    
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping(path = "/register",method = RequestMethod.GET)
    public String getRegisterPage(){
        return "/site/register";
    }

    @RequestMapping(path = "/login",method = RequestMethod.GET)
    public String getLoginPage(){
        return "/site/login";
    }

    @RequestMapping(path = "/register",method = RequestMethod.POST)
    public String register(Model model, User user){
        //主要处理判空，构造实体，构造激活邮件
        Map<String, Object> map = userService.register(user);
        if(map == null || map.isEmpty()){
            //map没有携带错误信息，则为正确注册,需要跳转到中转网页（携带注册成功的信息和最终目标网址）
            model.addAttribute("msg","注册成功,我们已经向您的邮箱发送了一封激活邮件,请尽快激活!");
            model.addAttribute("target","/index");
            return "/site/operate-result";
        }else{
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            model.addAttribute("emailMsg",map.get("emailMsg"));
            return "/site/register";
        }
    }


    /**
     * 点击激活码链接后的响应
     * http://localhost:8080/community/activation/111/act_code
     * @param model
     * @param userId
     * @param code
     * @return
     */
    @RequestMapping(path = "/activation/{userId}/{code}",method = RequestMethod.GET)
    public String activation(Model model, @PathVariable("userId") int userId,@PathVariable("code") String code){
        int ressult = userService.activation(userId,code);
        if(ressult == ACTIVATION_SUCCESS){
            model.addAttribute("msg","激活成功,您的账号已经可以正常使用了!");
            model.addAttribute("target","/login");
        }else if(ressult == ACTIVATION_REPEAT){
            model.addAttribute("msg","无效操作,该账号已经激活过了!");
            model.addAttribute("target","/login");
        }else{
            model.addAttribute("msg","激活失败,您提供的激活码不正确!");
            model.addAttribute("target","/index");
        }
        return "/site/operate-result";
    }

    /**
     * 发送验证码，同时自己要保存一份在服务器，等待校验
     * @param response
     */
    @RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response/*, HttpSession session*/){
        //生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);
        
        //存入session
        //session.setAttribute("kaptcha",text);
        
        //优化不存入session，尝试存入redis
        //验证码的归属
        String kaptchaOwner = CommunityUtil.generateUUID();
        
        //将临时凭证通过cookies传给用户，
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        //验证码60s过期
        cookie.setMaxAge(60);
        cookie.setPath(contextPath);
        response.addCookie(cookie);
        //将验证码存入redis
        String redisKey = RedisUtil.getKaptchaKey(kaptchaOwner);
        //将图片生成的验证码和刚设的键存入redis，
        redisTemplate.opsForValue().set(redisKey,text,60, TimeUnit.SECONDS);


        //将图片输出给浏览器
        response.setContentType("image/png");
        try {
            ServletOutputStream stream = response.getOutputStream();
            ImageIO.write(image,"png",stream);
        } catch (IOException e) {
            logger.error("验证码生成错误：" + e.getMessage());
        }

    }


    @RequestMapping(path = "/login",method = RequestMethod.POST)
    public String login(String username,String password,String code,boolean rememberme,
                        Model model/*,HttpSession session*/,HttpServletResponse response,
                        @CookieValue("kaptchaOwner") String kaptchaOwner){
        //检查验证码
        //String kaptcha = (String) session.getAttribute("kaptcha");
        String kaptcha = null;
        if(StringUtils.isNotBlank(kaptchaOwner)){
            String key = RedisUtil.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(key);
        }



        if(StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)){
            model.addAttribute("codeMsg","验证码不正确");
            return "/site/login";
        }
        //检查账号，密码
        int expiredSeconds = rememberme ? REMEMBERME_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        //传入
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        //判断是成功还是失败
        if(map.containsKey("ticket")){
            //设置cookies
            System.out.println(map.get("ticket").toString());
            Cookie cookie = new Cookie("ticket",  map.get("ticket").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSeconds);
            //返回cookies
            response.addCookie(cookie);
            return "redirect:/index";
        }else {
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            return "/site/login";
        }
    }

    @RequestMapping(path = "/logout", method = RequestMethod.GET)
    public String logout(@CookieValue("ticket") String ticket){
        userService.logout(ticket);
        SecurityContextHolder.clearContext();
        return "redirect:/login";
    }

    @RequestMapping(path = "/forget",method = RequestMethod.GET)
    public String forgetPassword(){
        return "/site/forget";
    }


    /**
     * 向目标邮箱发送验证码，并保存一份
     * @param model
     * @param email
     * @param session
     * @return
     */
    @RequestMapping(path = "/sendVerifyCode",method = RequestMethod.GET)
    public String sendCode(Model model,String email,HttpSession session) {
        //向目标发送验证码
        Map<String, Object> map = userService.sendVerifyCode(email);
        //正确生成验证码，邮箱无误
        if(map.containsKey("verifyCode")){
            System.out.println(map.get("verifyCode"));
            session.setAttribute(email+"_verifyCode",map.get("verifyCode"));
            //5min过时
            //session.setMaxInactiveInterval(60 * 5);
        }else{
            model.addAttribute("emailMsg",map.get("emailMsg"));
        }
        return "/site/forget";
    }

    /**
     * 处理点击重置密码的请求
     * @param model
     * @param email
     * @param password
     * @return
     */
    @RequestMapping(path = "/forget" ,method = RequestMethod.POST)
    public String resetPassword(Model model,String email,String password,String code,HttpSession session){
        //从session中获取存储的验证码
        System.out.println(session.getAttribute(email+"_verifyCode").toString());
        String verifyCode = session.getAttribute(email+"_verifyCode").toString();
        if (StringUtils.isEmpty(code) || StringUtils.isBlank(code) || !verifyCode.equalsIgnoreCase(code)){
            model.addAttribute("codeMsg","验证码错误！");
            return "/site/forget";
        }
        Map<String,Object> map = userService.resetPassword(email ,password);
        if (map.containsKey("updateRows")){
            //成功更改
            model.addAttribute("msg", "你已重新修改密码，请重新登录！");
            model.addAttribute("target", "/site/login");
            return "/site/login";
        }else{
            model.addAttribute("emailMsg",map.get("emailMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            return "/site/forget";
        }
    }

}
